package com.kf.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kf.handler.MyException;
import com.kf.mapper.PermissionMapper;
import com.kf.mapper.RolePermsMapper;
import com.kf.mapper.TreePermMapper;
import com.kf.pojo.*;
import com.kf.pojo.form.AddMenuForm;
import com.kf.service.PermissionService;
import com.kf.service.RolePermsService;
import com.kf.service.RoleService;
import com.kf.service.UserRoleService;
import com.kf.util.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 康峰
 * @since 2022-10-16
 */
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService {
    @Resource
    PermissionMapper permissionMapper;
    @Resource
    RolePermsMapper rolePermsMapper;
    @Override
    public  List<Permission> findAll(){

        return permissionMapper.selectList(null);
    }

    @Override
    public  Permission getPermsName(int perId){

        QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("perm_id",perId);

        return permissionMapper.selectOne(queryWrapper);
    }




    @Autowired
    protected PermissionService permissionService;
    @Autowired
    protected TreePermMapper treePermMapper;


    @Override
    public List<Permission> selectAllXia(int perms_id){
        List<Permission> permissions = new ArrayList<>();

        List<TreePerm> allChildrenTreeByid = treePermMapper.findAllChildrenTreeByid(perms_id);
        if(allChildrenTreeByid!=null){
            for (TreePerm treePerm : allChildrenTreeByid) {
                Permission child = permissionService.getPermsName(treePerm.getMemberKey());
                List<Permission> permissions1= selectAllXia(treePerm.getMemberKey());
                child.setChildren(permissions1);
                permissions.add(child);
            }
            return permissions;
        }else{

            return permissions;
        }
    }
    @Resource
    UserRoleService userRoleService;
    @Resource
    RolePermsService rolePermsService;
    @Resource
    RoleService roleService;
    @Override
    public List<Permission> findMyPerms(User user){
        List<Permission> permissions = new ArrayList<>();
        List<UserRole> userRole = userRoleService.getUserRole(user.getUserId());
        for (UserRole userrole : userRole) {
            System.out.println("角色id"+userrole.getRoleId());
            Role role = roleService.getRole(userrole.getRoleId());

            List<RolePerms> perms = rolePermsService.getPerms(userrole.getRoleId());
            for (RolePerms perm : perms) {
                System.out.println("权限id"+perm.getPermId());
                Permission permission = permissionService.getPermsName(perm.getPermId());
                permissions.add(permission);
            }

        }
        System.out.println("111");
        List<Permission> permissionList = permissions.stream().distinct().collect(Collectors.toList());
        return permissionList;
    }
    @Override
    public Permission findChildren(Permission permission, List<Permission> list) {

        List children = new ArrayList<Permission>();
        for (Permission permission1 : list) {
            if (permission1.getParentId().equals(permission.getPermId())) {
                //递归调用
                children.add(findChildren(permission1, list));
            }

        }
        permission.setChildren(children);
        return permission;

    }
    @Override
    public List<Permission> listToTree(List<Permission> permissions) {
//        List<Permission> permissions = findMyPerms(user);
        List<Permission> tree = new ArrayList<Permission>();
        for (Permission permission : permissions) {
            if (permission.getParentId() ==3) {
                tree.add(findChildren(permission, permissions));
            }
        }
        for (Permission o : tree) {
            System.out.println(o);
        }
        System.out.println(tree);
        return tree;

    }
    @Override
    public void insertTreeperm(Permission permission){
        TreePerm treePerm = new TreePerm();
        //先把这个权限插入自身数据 例 2 0 0 2
        treePerm.setAncestorsKey(permission.getPermId());
        treePerm.setDistance(0);
        treePerm.setMemberKey(permission.getPermId());
        int insert = treePermMapper.insert(treePerm);
        if(permission.getParentId()==0){
            return;
        }
        treePerm.setAncestorsKey(permission.getParentId());
        treePerm.setDistance(1);
        treePerm.setMemberKey(permission.getPermId());
        treePermMapper.insert(treePerm);
        List<TreePerm> allParentByid = treePermMapper.findAllParentByid(permission.getParentId());
        for (TreePerm tree : allParentByid) {
            TreePerm treePerm1 = new TreePerm();
            treePerm1.setMemberKey(permission.getPermId());
            treePerm1.setDistance(tree.getDistance()+1);
            treePerm1.setAncestorsKey(tree.getAncestorsKey());
            int insert1 = treePermMapper.insert(treePerm1);
        }

    }

    @Override
    public List<Permission> treeToList(List<Permission>  permissionList,List<Permission> perIdList ) {


        for (Permission perms : permissionList) {
            perIdList.add(perms);

            if(perms.getChildren()!=null&&!perms.getChildren().isEmpty()){
//                perms.setChildren(null);
                treeToList(perms.getChildren(),perIdList);
            }
        }
        return perIdList;

    }

    @Override
    public void addMenu(AddMenuForm addMenuForm) {
        Permission permission = new Permission();
        permission.setBton(addMenuForm.getBton());
        permission.setPerms(addMenuForm.getPerms());
        permission.setIcon(addMenuForm.getIcon());
        permission.setPath(addMenuForm.getPath());
        permission.setPermsName(addMenuForm.getPermsName());
        permission.setParentId(addMenuForm.getParentId());
        QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id",addMenuForm.getParentId());
        List<Permission> permissionList = permissionMapper.selectList(queryWrapper);
        for (Permission permission1 : permissionList) {
            if(permission1.getPermsName().equals(permission.getPermsName())){
                throw new MyException(ResultCode.STUDENT_ADD_ERROR);
            }
        }
        permissionMapper.insert(permission);
        QueryWrapper<Permission> permissionQueryWrapper = new QueryWrapper<>();
        permissionQueryWrapper.eq("perms_name",permission.getPermsName())

        .eq("parent_id",permission.getParentId());
//        .eq("icon",permission.getIcon());
        Permission permission1 = permissionMapper.selectOne(permissionQueryWrapper);
        permissionService.insertTreeperm(permission1);

    }




    @Override
    public void updatePermision(AddMenuForm addMenuForm) {
        Permission permission = permissionService.getById(addMenuForm.getPermId());
        permission.setBton(addMenuForm.getBton());
        permission.setPerms(addMenuForm.getPerms());
        permission.setIcon(addMenuForm.getIcon());
        permission.setPath(addMenuForm.getPath());
        permission.setPermsName(addMenuForm.getPermsName());
        permission.setParentId(addMenuForm.getParentId());
        QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id",addMenuForm.getParentId());
        List<Permission> permissionList1 = permissionMapper.selectList(queryWrapper);

        Stream<Permission> permissionStream = permissionList1.stream().filter(x ->
                !x.getPermId().equals(permission.getPermId())
        );

        permissionStream.forEach(x->{
            if(x.getPermsName().equals(permission.getPermsName())){
                throw new MyException(ResultCode.CAI_ADD_ERROR3);
            }
        });
//        boolean remove = permissionList1.remove(permission);
//        System.out.println("remove"+remove);
//        for (Permission permission1 : permissionList1) {
//            System.out.println("permission=========>"+permission1);
//            if(permission1.getPermsName().equals(permission.getPermsName())){
//                throw new MyException(ResultCode.CAI_ADD_ERROR3);
//            }
//        }

        List<Permission> perms = selectAllXia(permission.getPermId());
        perms.add(permission);
        List<Permission> permIdList=new ArrayList<>();
        List<Permission> permissionList = permissionService.treeToList(perms, permIdList);
        for (Permission permission1 : permissionList) {
            permission1.setChildren(null);
            treePermMapper.deleteByIdtree(permission1.getPermId());
            insertTreeperm(permission1);
        }

        permissionMapper.updateById(permission);


//        treePermMapper.delete()

    }

    @Override
    public void deletePermision(int id) {
        Permission permission = permissionMapper.selectById(id);
        List<Permission> perms = selectAllXia(id);
        perms.add(permission);
        List<Permission> permIdList=new ArrayList<>();
        List<Permission> permissionList = permissionService.treeToList(perms, permIdList);
        for (Permission permission1 : permissionList) {
            permission1.setChildren(null);
            treePermMapper.deleteByIdtree(permission1.getPermId());
            QueryWrapper<RolePerms> rolePermsQueryWrapper = new QueryWrapper<>();
            rolePermsQueryWrapper.eq("perm_id",permission1.getPermId());
            rolePermsMapper.delete(rolePermsQueryWrapper);
            permissionMapper.deleteById(permission1.getPermId());
        }






}

}
